<!--
 * @页面名称:主页面查找替换
 * @描述: 
 * @作者: 
 * @Date:
-->
<template>
  <el-dialog :modelValue="modalSetting.visible" :title="modalSetting.title" :width="500" draggable @close="close">
    <el-form :model="replacementFormData" ref="replacementForm">
      <el-form-item label="选择字段:">
        <el-select v-model="replacementFormData.Field" style="width: 100%" @change="selectChange">
          <el-option v-for="item in selectList" :key="item.DDM_ID" :value="item.Field_Name" :label="item.DDM_CNName"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="查找内容:">
        <!-- 分类 -->
        <el-tree-select
          v-if="fieldName === 'Catalog_ID'"
          style="width: 100%"
          check-strictly
          v-model="replacementFormData.FindContent"
          node-key="Catalog_ID"
          :props="{ label: 'Catalog_Name', children: 'children' }"
          :data="transTree(catalogListDto, 'Catalog_ID', 'Catalog_Father')"
          :render-after-expand="false"
        />
        <!-- 部门 -->
        <el-tree-select
          v-else-if="fieldName === 'Dept_ID'"
          style="width: 100%"
          check-strictly
          v-model="replacementFormData.FindContent"
          node-key="DDL_ID"
          :props="{ label: 'DDL_Code', children: 'children' }"
          :data="transTree(dictionryStore.dictionaryObj['Dept_ID'], 'DDL_ID', 'DDL_FatherID')"
          :render-after-expand="false"
        />
        <!-- 状态 -->
        <el-select v-else-if="fieldName === 'Status'" v-model="replacementFormData.FindContent">
          <el-option v-for="item in StatusList" :key="item.name" :value="item.value" :label="item.name"> </el-option>
        </el-select>
        <!-- 字典数据 -->
        <el-select
          v-else-if="selectRuleData.FR_Rule?.includes('dictionary') && fieldName !== 'Dept_ID'"
          v-model="replacementFormData.FindContent"
        >
          <el-option
            v-for="item in dictionryStore.dictionaryObj[selectRuleData.FR_Rule.split(':')[1]]"
            :key="item.DDL_ID"
            :value="item.DDL_ID"
            :label="item.DDL_Name"
          >
          </el-option>
        </el-select>
        <!-- 日期格式 -->
        <el-date-picker
          v-else-if="fieldType === 'datetime'"
          class="datePick"
          v-model="replacementFormData.FindContent"
          type="date"
          placeholder="请选择日期"
        />
        <!-- 数字类型 -->
        <el-input
          v-else-if="
            (fieldType === 'int' || fieldType === 'long') &&
            !selectRuleData.FR_Rule?.includes('userInfo') &&
            !selectRuleData.FR_Rule?.includes('dictionary') &&
            !selectRuleData.FR_Rule?.includes('catalogConvert')
          "
          type="number"
          v-model.number="replacementFormData.FindContent"
        ></el-input>
        <!-- boolean 类型 -->
        <el-checkbox v-else-if="fieldType === 'bool'" v-model="replacementFormData.FindContent"></el-checkbox>
        <!-- 人员信息 -->
        <el-select v-else-if="selectRuleData.FR_Rule?.includes('userInfo')" v-model="replacementFormData.FindContent">
          <el-option v-for="item in userList" :key="item.U_ID" :value="item.U_ID" :label="item.U_CName"> </el-option>
        </el-select>
        <!-- 其他 -->
        <el-input v-else v-model="replacementFormData.FindContent"></el-input>
      </el-form-item>
      <el-form-item label="要替换为:">
        <!-- 分类 -->
        <el-tree-select
          v-if="fieldName === 'Catalog_ID'"
          style="width: 100%"
          check-strictly
          v-model="replacementFormData.ReplaceContent"
          node-key="Catalog_ID"
          :props="{ label: 'Catalog_Name', children: 'children' }"
          :data="transTree(catalogListDto, 'Catalog_ID', 'Catalog_Father')"
          :render-after-expand="false"
        />
        <!-- 部门 -->
        <el-tree-select
          v-else-if="fieldName === 'Dept_ID'"
          style="width: 100%"
          check-strictly
          v-model="replacementFormData.ReplaceContent"
          node-key="DDL_ID"
          :props="{ label: 'DDL_Code', children: 'children' }"
          :data="transTree(dictionryStore.dictionaryObj['Dept_ID'], 'DDL_ID', 'DDL_FatherID')"
          :render-after-expand="false"
        />
        <!-- 状态 -->
        <el-select v-else-if="fieldName === 'Status'" v-model="replacementFormData.ReplaceContent">
          <el-option v-for="item in StatusList" :key="item.name" :value="item.value" :label="item.name"> </el-option>
        </el-select>
        <!-- 字典数据 -->
        <el-select
          v-else-if="selectRuleData.FR_Rule?.includes('dictionary') && fieldName !== 'Dept_ID'"
          v-model="replacementFormData.ReplaceContent"
        >
          <el-option
            v-for="item in dictionryStore.dictionaryObj[selectRuleData.FR_Rule.split(':')[1]]"
            :key="item.DDL_ID"
            :value="item.DDL_ID"
            :label="item.DDL_Name"
          >
          </el-option>
        </el-select>
        <!-- 日期格式 -->
        <el-date-picker
          v-else-if="fieldType === 'datetime'"
          class="datePick"
          v-model="replacementFormData.ReplaceContent"
          type="date"
          placeholder="请选择日期"
        />
        <!-- 数字类型 -->
        <el-input
          v-else-if="
            (fieldType === 'int' || fieldType === 'long') &&
            !selectRuleData.FR_Rule?.includes('userInfo') &&
            !selectRuleData.FR_Rule?.includes('dictionary') &&
            !selectRuleData.FR_Rule?.includes('catalogConvert')
          "
          type="number"
          v-model.number="replacementFormData.ReplaceContent"
        ></el-input>
        <!-- boolean 类型 -->
        <el-checkbox v-else-if="fieldType === 'bool'" v-model="replacementFormData.ReplaceContent"></el-checkbox>
        <!-- 人员信息 -->
        <el-select v-else-if="selectRuleData.FR_Rule?.includes('userInfo')" v-model="replacementFormData.ReplaceContent">
          <el-option v-for="item in userList" :key="item.U_ID" :value="item.U_ID" :label="item.U_CName"> </el-option>
        </el-select>
        <!-- 其他 -->
        <el-input v-else v-model="replacementFormData.ReplaceContent"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="replace">应用替换</el-button>
      <el-button :disabled="subStatus" @click="submit">提交生效</el-button>
      <el-button @click="close">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, h } from "vue";
import { useDictionryStore } from "@/stores/modules/dictionary";
import { useDynamicStore } from "@/stores/modules/dynamic";
import { useCatalogStore } from "@/stores/modules/catalog";
import { useUserStore } from "@/stores/modules/user";
import { useAppStore } from "@/stores/modules/app";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { transTree } from "@/utils/util";
import { useRoute } from "vue-router";
import { ElMessageBox, ElSwitch } from "element-plus";
import ACrypto from "@/utils/crypto";
import RuleClass from "../../ts/FieldRule.ts";
import { cloneDeep } from "lodash-es";

const { proxy } = useCurrentInstance();
const props = defineProps({
  config: {
    type: Object,
    default: () => {
      return {};
    }
  }
});
// 弹框配置
const modalSetting = reactive({
  visible: false,
  title: "查找替换"
});
// pinia数据
const dynamicStore = useDynamicStore();
const dictionryStore = useDictionryStore();
const catalogStore = useCatalogStore();
const userStore = useUserStore();
const appStore = useAppStore();
// 表单绑定字段
const replacementFormData = reactive({
  Field: "",
  FindContent: null,
  ReplaceContent: null
});
// 表单实例
const replacementForm = ref();
// 获取路由
const route = useRoute();
// 路由携带的参数
const routeData = ref(route.query as any);
// 字段数据集合
const str = "DDM_Enable_Display_" + routeData.value.status;
const selectList = ref([]);
// 当前选中的数据类型
const fieldName = ref("");
// 字段类型
const fieldType = ref("String");
// 包含字典参数的数据
const selectRuleData = ref({});
// 状态列表
const StatusList = ref([
  { name: "收集", value: 1 },
  { name: "整理", value: 2 },
  { name: "保存", value: 3 },
  { name: "利用", value: 4 }
]);
// 操作人规则集合
const personRuleList = ref([]);
// 人员信息列表
const userList = computed(() => userStore.userList);
// 存放查找替换成功的目录数据，但还没提交，免于大循环提交全部
const tempReplaceData = ref([]);
// 替换数据数量
const countNum = ref(0);
// 勾选数据的深拷贝数据
const CopyData = ref([]);
const catalogListDto = computed(() => {
  return catalogStore.catalogList.map((item: any) => {
    return {
      ...item,
      Catalog_Name: `(${item.Catalog_Code})${item.Catalog_Name} `
    };
  });
});
// 提交按钮状态
const subStatus = ref(true);
// 弹框弹出
const show = (list: any[]) => {
  modalSetting.visible = true;
  selectList.value = list;
  replacementForm.value?.resetFields();
  if (props.config.type === 1) {
    CopyData.value = cloneDeep(dynamicStore.tableSelect);
  } else {
    CopyData.value = cloneDeep(dynamicStore.childTableSelect);
  }
};
// 获取数据表
const getTableName = (id: any) => {
  if (dynamicStore.datasheet.length > 0) {
    fieldType.value = dynamicStore.datasheet.filter((v: any) => v.DbColumnName === fieldName.value)[0].DataType;
  } else {
    proxy.$vueAxios
      .post(
        "Master_Base_FormModel_Table/GetConditional",
        {
          order: "FMT_Type ASC",
          dtoList: [
            {
              fieldName: "FMT_ID",
              fieldValue: id
            }
          ]
        },
        { noLoading: true }
      )
      .then((res: any) => {
        proxy.$vueAxios
          .get("Table/column/get", { tableName: res.List[0].FMT_TableName }, { noLoading: true })
          .then((res2: any) => {
            if (res.Mark) {
              dynamicStore.setDatasheet(res2.List);
              fieldType.value = res2.List.filter((v: any) => v.DbColumnName === fieldName.value)[0].DataType;
            }
          });
      });
  }
};
// 选择框改变事件
const selectChange = (value: any) => {
  fieldName.value = value;
  // 获取到选择的完整数据
  const findItem = selectList.value.find((v: any) => v.Field_Name === value);
  if (dictionryStore.ruleList.length > 0) {
    selectRuleData.value =
      dictionryStore.ruleList
        .filter((v: any) => v.FR_Enable && v.FR_RuleType === "display")
        .filter((v: any) => v.FR_TableField === findItem.Field_Name)[0] || [];
  } else {
    proxy.$vueAxios
      .post(
        "Master_Base_FieldRule/GetConditional",
        {
          order: "FR_Order asc",
          dtoList: [{ fieldName: "FMT_ID", fieldValue: findItem.FMT_ID }]
        },
        { noLoading: true }
      )
      .then((res: any) => {
        if (res.Mark) {
          dictionryStore.getRuleList(res.List);
          // 获取当前选中数据的字段规则
          selectRuleData.value =
            res.List.filter((v: any) => v.FR_Enable && v.FR_RuleType === "display").filter(
              (v: any) => v.FR_TableField === findItem.Field_Name
            )[0] || [];
        }

        // personRuleList.value = res.List.filter(
        //   (v: any) => v.FR_Enable && v.FR_RuleType === "display" && v.FR_Rule.includes("userInfo")
        // );
      });
  }
  getTableName(findItem.FMT_ID);
  replacementFormData.ReplaceContent = undefined;
  replacementFormData.FindContent = undefined;
};
// 应用替换(本地预览)
const replace = async () => {
  subStatus.value = false;
  tempReplaceData.value = []; // 置空临时存储匹配成功的集合
  countNum.value = 0;
  if (!replacementFormData.Field) {
    proxy.$message.warning("请选择要替换的字段!");
    return false;
  }
  if (replacementFormData.FindContent === replacementFormData.ReplaceContent) {
    proxy.$message.warning("替换与被替换内容不能相同!");
    return false;
  }
  if (props.config.type === 1) {
    const jmList = dynamicStore.visibleConfig.FieldRule.filter((v: any) => v.FR_RuleType === "display").filter((v: any) =>
      v.FR_Rule.toLowerCase().includes("jm")
    );
    for (let i = 0; i < CopyData.value.length; i++) {
      const item = CopyData.value[i];
      let itemValue = item[replacementFormData.Field];
      const item2 = dynamicStore.tableSelect.filter((v: any) => v.Record_ID === item.Record_ID)[0];
      item2[replacementFormData.Field] = itemValue;
      // dynamicStore.tableSelect.forEach((item: any) => {
      jmList.forEach((v: any) => {
        if (replacementFormData.Field === v.FR_TableField) {
          // 对加密字段转换
          item2[replacementFormData.Field] = ACrypto.getSS(item2[replacementFormData.Field]);
        }
      });
      // 如果为int类型
      if (Number.isInteger(replacementFormData.FindContent)) {
        if (item2[replacementFormData.Field] == replacementFormData.FindContent) {
          item2[replacementFormData.Field] = replacementFormData.ReplaceContent;
          countNum.value++;
          tempReplaceData.value.push(item2);
        }
      } else {
        if (String(item2[replacementFormData.Field]).indexOf(String(replacementFormData.FindContent)) > -1) {
          countNum.value++;
          const regExp = new RegExp(String(replacementFormData.FindContent), "g");
          item2[replacementFormData.Field] = item2[replacementFormData.Field].replace(
            regExp,
            String(replacementFormData.ReplaceContent ? replacementFormData.ReplaceContent : "")
          );
          tempReplaceData.value.push(item2);
        } else if (!replacementFormData.FindContent) {
          countNum.value++;
          item2[replacementFormData.Field] = replacementFormData.ReplaceContent;
          tempReplaceData.value.push(item2);
        }
      }
    }
    // });
    ElMessageBox({
      title: "提示",
      // Should pass a function if VNode contains dynamic props
      message: h("div", null, [
        h("p", null, `您选中了${dynamicStore.tableSelect.length}条数据`),
        h("p", null, `有效匹配到了${countNum.value}条数据`)
      ])
    });
  }
  if (props.config.type === 2) {
    const jmList = dynamicStore.childVisibleConfig.FieldRule.filter((v: any) => v.FR_RuleType === "display").filter((v: any) =>
      v.FR_Rule.toLowerCase().includes("jm")
    );
    for (let i = 0; i < CopyData.value.length; i++) {
      const item = CopyData.value[i];
      let itemValue = item[replacementFormData.Field];
      const item2 = dynamicStore.childTableSelect.filter((v: any) => v.Record_ID === item.Record_ID)[0];
      item2[replacementFormData.Field] = itemValue;
      // dynamicStore.tableSelect.forEach((item: any) => {
      jmList.forEach((v: any) => {
        if (replacementFormData.Field === v.FR_TableField) {
          // 对加密字段转换
          item2[replacementFormData.Field] = ACrypto.getSS(item2[replacementFormData.Field]);
        }
      });
      // 如果为int类型
      if (Number.isInteger(replacementFormData.FindContent)) {
        if (item2[replacementFormData.Field] == replacementFormData.FindContent) {
          item2[replacementFormData.Field] = replacementFormData.ReplaceContent;
          countNum.value++;
          tempReplaceData.value.push(item2);
        }
      } else {
        if (String(item2[replacementFormData.Field]).indexOf(String(replacementFormData.FindContent)) > -1) {
          countNum.value++;
          const regExp = new RegExp(String(replacementFormData.FindContent), "g");
          item2[replacementFormData.Field] = item2[replacementFormData.Field].replace(
            regExp,
            String(replacementFormData.ReplaceContent ? replacementFormData.ReplaceContent : "")
          );
          tempReplaceData.value.push(item2);
        } else if (!replacementFormData.FindContent) {
          countNum.value++;
          item2[replacementFormData.Field] = replacementFormData.ReplaceContent;
          tempReplaceData.value.push(item2);
        }
      }
    }
    // dynamicStore.childTableSelect.forEach((item: any) => {
    //   // 如果为int类型
    //   if (Number.isInteger(replacementFormData.FindContent)) {
    //     if (item[replacementFormData.Field] == replacementFormData.FindContent) {
    //       item[replacementFormData.Field] = replacementFormData.ReplaceContent;
    //       countNum.value++;
    //       tempReplaceData.value.push(item);
    //     }
    //   } else {
    //     if (String(item[replacementFormData.Field]).indexOf(String(replacementFormData.FindContent)) > -1) {
    //       countNum.value++;
    //       item[replacementFormData.Field] = item[replacementFormData.Field].replace(
    //         String(replacementFormData.FindContent),
    //         String(replacementFormData.ReplaceContent)
    //       );
    //       tempReplaceData.value.push(item);
    //     }
    //   }
    // });
    ElMessageBox({
      title: "提示",
      // Should pass a function if VNode contains dynamic props
      message: h("div", null, [
        h("p", null, `您选中了${dynamicStore.childTableSelect.length}条数据`),
        h("p", null, `有效匹配到了${countNum.value}条数据`)
      ])
    });
  }
};
// 提交生效
const submit = async () => {
  if (!countNum.value) {
    proxy.$message.warning("未匹配到数据!");
    return;
  }
  const { visibleConfig, childVisibleConfig } = dynamicStore;
  appStore.LoadingConfig.contentLoading = true;
  appStore.LoadingConfig.contentTip = "处理中...";
  // 获取到加密字段规则
  const jmList = dynamicStore.visibleConfig.FieldRule.filter((v: any) => v.FR_RuleType === "display").filter((v: any) =>
    v.FR_Rule.toLowerCase().includes("jm")
  );
  try {
    for (let i = 0; i < tempReplaceData.value.length; i++) {
      delete tempReplaceData.value[i].checkbox;
      const FieldRuleClass = new RuleClass({
        modalFormData: tempReplaceData.value[i],
        fieldName: fieldName.value,
        ruleList: dynamicStore.visibleConfig.FieldRule.filter((v: any) => v.FR_Enable === true),
        tableName: props.config.type === 1 ? visibleConfig.FMT.FMT_TableName : childVisibleConfig.FMT.FMT_TableName,
        type: props.config.type === 1 ? 1 : 2
      }); // 执行字段规则类方法
      // 循环比对当前字段是否为加密字段
      jmList.forEach((v: any) => {
        if (replacementFormData.Field === v.FR_TableField) {
          // 字段转换成加密字段
          tempReplaceData.value[i][replacementFormData.Field] = ACrypto.setSS(
            tempReplaceData.value[i][replacementFormData.Field]
          );
        }
      });
      await FieldRuleClass.fieldRuleEvent2();
      const param = {
        list: [{ ...tempReplaceData.value[i] }],
        tableName: props.config.type === 1 ? visibleConfig.FMT.FMT_TableName : childVisibleConfig.FMT.FMT_TableName
      };
      await proxy.$vueAxios.put("Dynamic", param, { noLoading: true }).then((res: any) => {
        console.log(res);
      });
      appStore.LoadingConfig.contentTip = `处理中(${i + 1}/${tempReplaceData.value.length})`;
      if (replacementFormData.Field === "Catalog_ID") {
        const index = dynamicStore.tableData.findIndex((v: any) => v.Record_ID === tempReplaceData.value[i].Record_ID);
        if (index > -1) {
          dynamicStore.tableData.splice(index, 1);
        }
      }
    }
    modalSetting.visible = false;
    appStore.LoadingConfig.contentLoading = false;
    proxy.$message.success("替换成功!");
  } catch (err) {
    appStore.LoadingConfig.contentLoading = true;
  }
  tempReplaceData.value = []; // 置空临时存储匹配成功的集合
};
// 取消事件
const close = () => {
  for (let i = 0; i < tempReplaceData.value.length; i++) {
    const item = tempReplaceData.value[i];
    CopyData.value.filter((v: any) => {
      if (v.Record_ID === item.Record_ID) {
        return (item[replacementFormData.Field] = v[replacementFormData.Field]);
      }
    });
  }
  modalSetting.visible = false;
};
defineExpose({ show });
</script>

<style scoped lang="scss">
:deep(.datePick) {
  width: 100%;
  .el-input__wrapper {
    width: -webkit-fill-available;
  }
}
</style>
